/**
 * 
 */
package com.tunan.config;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.sql.DataSource;

import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;

import com.tunan.system.persistence.model.SpringContextUtil;

public final class SequenceKeyFcatory {
	private final static SequenceKeyFcatory _INSTANCE = new SequenceKeyFcatory();
	private static DataSource ds;

	private SequenceKeyFcatory() {
		MyBatisConfig mybatisConfig=(MyBatisConfig)SpringContextUtil.getBean("mybatisConfig");
		ds = mybatisConfig.primaryDataSource();
	}

	private static final ConcurrentMap<String, OracleSequenceMaxValueIncrementer> sequenceMap = new ConcurrentHashMap<String, OracleSequenceMaxValueIncrementer>();

	public static SequenceKeyFcatory getInstance() {
		return _INSTANCE;
	}

	public long getNextValue(String sequenceName) {
		OracleSequenceMaxValueIncrementer osi =sequenceMap.keySet().size()==0?null:sequenceMap.get(sequenceName);
		if (osi == null) {
			osi = new OracleSequenceMaxValueIncrementer(ds, sequenceName);
			sequenceMap.put(sequenceName, osi);
		}

		return osi.nextLongValue();
	}
}
